/**
 * Copyright 2012 Meruvian
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.yama.dao;

import javax.persistence.TypedQuery;

import org.meruvian.yama.persistence.EntityListWrapper;
import org.meruvian.yama.persistence.LogInformation.StatusFlag;
import org.meruvian.yama.persistence.access.PersistenceDAO;
import org.springframework.stereotype.Repository;

import com.example.yama.entity.Item;

/**
 * @author Dian Aditya
 * 
 */
@Repository
public class ItemDAO extends PersistenceDAO<Item> {
	public EntityListWrapper<Item> getAllByName(String name, int limit, int page) {
		String criteria = "i.logInformation.statusFlag = ?"
				+ " AND i.name like ?";

		Object[] parameters = { StatusFlag.ACTIVE, "%" + name + "%" };

		// SELECT i FROM Item i WHERE ${criteria}
		TypedQuery<Item> query = createQuery(Item.class, "i", "i", criteria,
				parameters);

		// SELECT COUNT(i) FROM Item c WHERE ${criteria}
		TypedQuery<Long> queryCount = createQuery(Long.class, "COUNT(i)", "i",
				criteria, parameters);

		if (limit > 0) {
			query.setMaxResults(limit);
		}

		query.setFirstResult(page * limit);

		EntityListWrapper<Item> paging = new EntityListWrapper<Item>();
		paging.setEntityList(query.getResultList());
		paging.setRowCount(queryCount.getSingleResult());
		paging.setCurrentPage(page);
		paging.setLimit(limit);

		return paging;
	}
}
